package com.citywithincity.apo;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import com.citywithincity.cache.Cache;
import com.citywithincity.cache.CacheUtil;
import com.citywithincity.cache.DefCachePolicy;
import com.citywithincity.cache.cachePolicy.CachePolicy;
import com.damai.action.aop.Interceptor;
import com.damai.action.aop.InterceptorInit;
import com.damai.action.aop.Invoker;

public class CacheInterceptor implements Interceptor,InterceptorInit {

	private String keyFormat;
	private CachePolicy cachePolicy;
	private static final CachePolicy DEFAULT_CACHE_POLICY = new DefCachePolicy();
	
	
	@Override
	public Object invoke(Invoker invoker, HttpServletRequest request, Object[] args) {
		//key为
		String key = String.format(keyFormat, args);
		Object cachedValue = CacheUtil.get(key);
		if(cachedValue==null){
			synchronized (this) {
				cachedValue = CacheUtil.get(key);
				if(cachedValue==null){
					cachedValue = invoker.invoke(request, args);
					CacheUtil.set(key, cachedValue,cachePolicy.getTimeout());
				}
			}
		}
		return cachedValue;
	}

	@Override
	public void init(Class<?> controllerClass, Method method) {
		Cache cache = method.getAnnotation(Cache.class);
		String key = null;
		
		
		if(cache==null){
			cachePolicy = DEFAULT_CACHE_POLICY;
			key = controllerClass.getSimpleName() + ":" + method.getName();
		}else{
			key = cache.key();
			Class<? extends CachePolicy> cachePolicyClass = cache.cachePolicy();
			try {
				cachePolicy = cachePolicyClass.newInstance();
			} catch (Exception e) {
				throw new RuntimeException("初始化"+cachePolicyClass.getName()+"失败",e);
			} 
		}
		
		StringBuilder sb = new StringBuilder(key);
		Class<?>[] types = method.getParameterTypes();
		for (Class<?> type : types) {
			sb.append(":").append("%s");
		}
		this.keyFormat = sb.toString();
		
	}

}
